﻿using System;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
using Felbot.Interface;
using Felbot.IO;

namespace Felbot {
    /// <summary>A little form that allows the user to store and use a list of CD-keys.</summary>
    public partial class frmCDKeyManager : Form {
        private frmProfileConfiguration m_frmProfileConfig;
        private INIControl m_CdKeyFile;

        /// <summary>Creates a new CD-key form.</summary>
        /// <param name="config">The configuration panel that opened it.</param>
        public frmCDKeyManager(frmProfileConfiguration config) {
            InitializeComponent();
            m_frmProfileConfig = config;
            LoadCdKeys();
        }

        /// <summary>Creates a new CD-key form.</summary>
        public frmCDKeyManager() {
            InitializeComponent();
            btnSetKey.Enabled = false;
            btnAddKey.Enabled = false;
            LoadCdKeys();
        }

        private void LoadCdKeys() {
            m_CdKeyFile = new INIControl(Program.ApplicationFolder + "\\cdkeys.fbf", null);
            m_CdKeyFile.LoadSettings();
            int count = m_CdKeyFile.GetSetting("Keys", "Count").ToInteger(0);
            string key;
            int client;
            for (int i = 0; i < count; i++) {
                key = m_CdKeyFile.GetSetting("Keys", "Key" + i.ToString()).ToString("");
                client = m_CdKeyFile.GetSetting("Keys", "Client" + i.ToString()).ToInteger(0);
                lvKeys.Items.Add(key, key, client);
            }
        }

        private void frmCDKeyManager_FormClosing(object sender, FormClosingEventArgs e) {
            m_CdKeyFile.SetSetting("Keys", "Count", Setting.FromInteger(lvKeys.Items.Count));
            for (int i = 0; i < lvKeys.Items.Count; i++) {
                m_CdKeyFile.SetSetting("Keys", "Key" + i.ToString(), Setting.FromString(lvKeys.Items[i].Text));
                m_CdKeyFile.SetSetting("Keys", "Client" + i.ToString(), Setting.FromInteger(lvKeys.Items[i].ImageIndex));
            }
            m_CdKeyFile.SaveSettings();
        }

        private void lvKeys_SelectedIndexChanged(object sender, EventArgs e) {
            btnEdit.Enabled = (lvKeys.SelectedItems.Count == 1);
            btnRemove.Enabled = (lvKeys.SelectedItems.Count > 0);
            if (m_frmProfileConfig != null) {
                btnSetKey.Enabled = (lvKeys.SelectedItems.Count == 1);
                if (lvKeys.SelectedItems.Count == 2) {
                    switch (lvKeys.SelectedItems[0].ImageIndex) {
                        default:
                            break;

                        case 2: //d2
                            if (lvKeys.SelectedItems[1].ImageIndex == 3) //d2x
                                btnSetKey.Enabled = true;
                            break;

                        case 3: //d2x
                            if (lvKeys.SelectedItems[1].ImageIndex == 2) //d2
                                btnSetKey.Enabled = true;
                            break;

                        case 5: //w3
                            if (lvKeys.SelectedItems[1].ImageIndex == 6) //w3x
                                btnSetKey.Enabled = true;
                            break;

                        case 6: //w3x
                            if (lvKeys.SelectedItems[1].ImageIndex == 5) //w3
                                btnSetKey.Enabled = true;
                            break;
                    }
                }
            }
        }

        private void btnSetKey_Click(object sender, EventArgs e) {
            if (m_frmProfileConfig == null)
                return;
            for (int i = 0; i < lvKeys.SelectedItems.Count && lvKeys.SelectedItems.Count <= 2; i++) {
                switch (lvKeys.SelectedItems[i].ImageIndex) {
                    default:
                        break;

                    case 1: //sc
                    case 2: //d2
                    case 4: //w2
                    case 5: //w3
                        m_frmProfileConfig.txtConCdkey.Text = lvKeys.SelectedItems[i].Text;
                        break;

                    case 3: //d2x
                    case 6: //w3x
                        m_frmProfileConfig.txtConExpCdkey.Text = lvKeys.SelectedItems[i].Text;
                        break;

                }
            }
        }

        private void btnAddKey_Click(object sender, EventArgs e) {
            if (m_frmProfileConfig == null)
                return;
            string key = "";
            int index = 0;
            string keyExp = "";
            int indexExp = 0;
            switch (m_frmProfileConfig.cboConClient.SelectedIndex) {
                default:
                    break;
                case 9: //w2
                    key = m_frmProfileConfig.txtConCdkey.Text;
                    index = 4;
                    break;
                case 2: //scj
                case 3: //sc
                case 4: //scx
                    key = m_frmProfileConfig.txtConCdkey.Text;
                    index = 1;
                    break;
                case 7: //d2
                    key = m_frmProfileConfig.txtConCdkey.Text;
                    index = 2;
                    break;
                case 8: //d2x
                    key = m_frmProfileConfig.txtConCdkey.Text;
                    index = 2;
                    keyExp = m_frmProfileConfig.txtConExpCdkey.Text;
                    indexExp = 3;
                    break;
                case 10: //w3
                    key = m_frmProfileConfig.txtConCdkey.Text;
                    index = 5;
                    break;
                case 11: //w3x
                    key = m_frmProfileConfig.txtConCdkey.Text;
                    index = 5;
                    keyExp = m_frmProfileConfig.txtConExpCdkey.Text;
                    indexExp = 6;
                    break;
            }
            if (key.Length > 0 && index != 0)
                if (!lvKeys.Items.ContainsKey(key))
                    lvKeys.Items.Add(key, key, index);
            if (keyExp.Length > 0 && indexExp != 0)
                if (!lvKeys.Items.ContainsKey(keyExp))
                    lvKeys.Items.Add(keyExp, keyExp, indexExp);
        }

        private void btnAdd_Click(object sender, EventArgs e) {
            frmCDKeyEditor editor = new frmCDKeyEditor("", 0);
            if (editor.ShowDialog() == DialogResult.OK) {
                lvKeys.Items.Add(editor.m_Key, editor.m_Key, editor.m_Index);
            }
        }

        private void btnEdit_Click(object sender, EventArgs e) {
            if (lvKeys.SelectedItems.Count == 1) {
                frmCDKeyEditor m_frmEditor = new frmCDKeyEditor(lvKeys.SelectedItems[0].Text, lvKeys.SelectedItems[0].ImageIndex);
                if (m_frmEditor.ShowDialog() == DialogResult.OK) {
                    int index = lvKeys.SelectedItems[0].Index;
                    lvKeys.Items.Remove(lvKeys.SelectedItems[0]);
                    lvKeys.Items.Insert(index, m_frmEditor.m_Key, m_frmEditor.m_Key, m_frmEditor.m_Index);
                }
            }
        }

        private void btnRemove_Click(object sender, EventArgs e) {
            foreach (ListViewItem item in lvKeys.SelectedItems) {
                lvKeys.Items.Remove(item);
            }
        }

        private void btnDone_Click(object sender, EventArgs e) {
            this.DialogResult = DialogResult.OK;
            this.Close();
        }

        private class frmCDKeyEditor : Form {
            public string m_Key;
            public int m_Index;

            public frmCDKeyEditor(string key, int index) {
                InitializeComponent();
                m_Key = key;
                m_Index = index;
            }

            /// <summary>
            /// Required designer variable.
            /// </summary>
            private IContainer components = null;

            /// <summary>
            /// Clean up any resources being used.
            /// </summary>
            /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
            protected override void Dispose(bool disposing) {
                if (disposing && (components != null)) {
                    components.Dispose();
                }
                base.Dispose(disposing);
            }

            #region Windows Form Designer generated code

            /// <summary>
            /// Required method for Designer support - do not modify
            /// the contents of this method with the code editor.
            /// </summary>
            private void InitializeComponent() {
                this.components = new Container();
                this.btnOK = new Button();
                this.btnCancel = new Button();
                this.txtKey = new TextBox();
                this.cboClient = new ComboBox();
                this.SuspendLayout();
                // 
                // btnOK
                // 
                this.btnOK.Anchor = ((AnchorStyles) ((AnchorStyles.Top | AnchorStyles.Right)));
                this.btnOK.DialogResult = DialogResult.OK;
                this.btnOK.Location = new Point(200, 6);
                this.btnOK.Name = "btnOK";
                this.btnOK.Size = new Size(112, 23);
                this.btnOK.TabIndex = 3;
                this.btnOK.Text = "OK";
                this.btnOK.UseVisualStyleBackColor = true;
                this.btnOK.Click += new EventHandler(btnOK_Click);
                // 
                // btnCancel
                // 
                this.btnCancel.Anchor = ((AnchorStyles) ((AnchorStyles.Top | AnchorStyles.Right)));
                this.btnCancel.DialogResult = DialogResult.Cancel;
                this.btnCancel.Location = new Point(200, 35);
                this.btnCancel.Name = "btnCancel";
                this.btnCancel.Size = new Size(112, 23);
                this.btnCancel.TabIndex = 2;
                this.btnCancel.Text = "Cancel";
                this.btnCancel.UseVisualStyleBackColor = true;
                this.btnCancel.Click += new EventHandler(btnCancel_Click);
                // 
                // txtKey
                // 
                this.txtKey.Anchor = ((AnchorStyles) ((AnchorStyles.Top | AnchorStyles.Left)));
                this.txtKey.Location = new Point(6, 6);
                this.txtKey.Name = "txtKey";
                this.txtKey.Size = new Size(182, 22);
                this.txtKey.TabIndex = 0;
                // 
                // cboClient
                // 
                this.cboClient.Anchor = ((AnchorStyles) ((AnchorStyles.Top | AnchorStyles.Left)));
                this.cboClient.DropDownStyle = ComboBoxStyle.DropDownList;
                this.cboClient.Items.Add("");
                this.cboClient.Items.Add("StarCraft");
                this.cboClient.Items.Add("Diablo II");
                this.cboClient.Items.Add("Diablo II: Lord of Destruction");
                this.cboClient.Items.Add("WarCraft II: Battle.net Edition");
                this.cboClient.Items.Add("WarCraft III");
                this.cboClient.Items.Add("WarCraft III: The Frozen Throne");
                this.cboClient.Location = new Point(6, 35);
                this.cboClient.Name = "cboClient";
                this.cboClient.Size = new Size(182, 22);
                this.cboClient.TabIndex = 1;
                // 
                // frmCDKeyManager
                // 
                this.AcceptButton = this.btnOK;
                this.AutoScaleDimensions = new SizeF(6F, 13F);
                this.AutoScaleMode = AutoScaleMode.Font;
                this.CancelButton = this.btnCancel;
                this.Controls.Add(this.btnOK);
                this.Controls.Add(this.btnCancel);
                this.Controls.Add(this.txtKey);
                this.Controls.Add(this.cboClient);
                this.ClientSize = new Size(324, 85);
                this.FormBorderStyle = FormBorderStyle.FixedToolWindow;
                this.MaximizeBox = false;
                this.MinimizeBox = false;
                this.Name = "frmCDKeyEditor";
                this.ShowIcon = false;
                this.ShowInTaskbar = false;
                this.Text = "CD-Key Editor";
                this.TopMost = true;
                this.Load += new EventHandler(frmCDKeyEditor_Load);
                this.ResumeLayout(false);

            }

            private Button btnOK;
            private Button btnCancel;
            private TextBox txtKey;
            private ComboBox cboClient;

            #endregion

            private void frmCDKeyEditor_Load(object sender, EventArgs e) {
                txtKey.Text = m_Key;
                cboClient.SelectedIndex = m_Index;
            }

            void btnCancel_Click(object sender, EventArgs e) {
                this.DialogResult = btnCancel.DialogResult;
                this.Close();
            }

            void btnOK_Click(object sender, EventArgs e) {
                m_Index = cboClient.SelectedIndex;
                switch (m_Index) {
                    default:
                        m_Key = txtKey.Text.Replace("-", "").Trim();
                        if (MessageBox.Show("No client is associated with this key." +
                                        "Continue?",
                                        "CD-Key Editor",
                                        MessageBoxButtons.YesNo,
                                        MessageBoxIcon.Exclamation,
                                        MessageBoxDefaultButton.Button2)
                                == DialogResult.No) {
                            return;
                        }
                        break;

                    case 1: //sc
                        m_Key = txtKey.Text.Replace("-", "").Trim();
                        if (m_Key.Length != 13 && m_Key.Length != 26) {
                            if (MessageBox.Show("This StarCraft key is not the correct length." +
                                            "Continue?",
                                            "CD-Key Editor",
                                            MessageBoxButtons.YesNo,
                                            MessageBoxIcon.Exclamation,
                                            MessageBoxDefaultButton.Button2)
                                    == DialogResult.No) {
                                return;
                            }
                        }
                        if (m_Key.Length == 13) {
                            foreach (char c in m_Key) {
                                if (!char.IsDigit(c)) {
                                    if (MessageBox.Show("This StarCraft key is not valid." +
                                                    "Continue?",
                                                    "CD-Key Editor",
                                                    MessageBoxButtons.YesNo,
                                                    MessageBoxIcon.Exclamation,
                                                    MessageBoxDefaultButton.Button2)
                                            == DialogResult.Yes) {
                                        break;
                                    } else {
                                        return;
                                    }
                                }
                            }
                            m_Key = m_Key.Substring(0, 4) + "-"
                                + m_Key.Substring(4, 5) + "-"
                                + m_Key.Substring(9, 4);
                        } else {
                            foreach (char c in m_Key) {
                                if (!char.IsLetterOrDigit(c)) {
                                    if (MessageBox.Show("This StarCraft key is not valid." +
                                                    "Continue?",
                                                    "CD-Key Editor",
                                                    MessageBoxButtons.YesNo,
                                                    MessageBoxIcon.Exclamation,
                                                    MessageBoxDefaultButton.Button2)
                                            == DialogResult.Yes) {
                                        break;
                                    } else {
                                        return;
                                    }
                                }
                            }
                            m_Key = m_Key.Substring(0, 6) + "-"
                                + m_Key.Substring(6, 4) + "-"
                                + m_Key.Substring(10, 6) + "-"
                                + m_Key.Substring(16, 4) + "-"
                                + m_Key.Substring(20, 6);
                        }
                        break;

                    case 2: //d2
                    case 3: //d2x
                        m_Key = txtKey.Text.Replace("-", "").Trim();
                        if (m_Key.Length != 16 && m_Key.Length != 26) {
                            if (MessageBox.Show("This Diablo II key is not the correct length." +
                                            "Continue?",
                                            "CD-Key Editor",
                                            MessageBoxButtons.YesNo,
                                            MessageBoxIcon.Exclamation,
                                            MessageBoxDefaultButton.Button2)
                                    == DialogResult.No) {
                                return;
                            }
                        }
                        foreach (char c in m_Key) {
                            if (!char.IsLetterOrDigit(c)) {
                                if (MessageBox.Show("This Diablo II key is not valid." +
                                                "Continue?",
                                                "CD-Key Editor",
                                                MessageBoxButtons.YesNo,
                                                MessageBoxIcon.Exclamation,
                                                MessageBoxDefaultButton.Button2)
                                        == DialogResult.Yes) {
                                    break;
                                } else {
                                    return;
                                }
                            }
                        }
                        if (m_Key.Length == 16) {
                            m_Key = m_Key.Substring(0, 4) + "-"
                                + m_Key.Substring(4, 4) + "-"
                                + m_Key.Substring(8, 4) + "-"
                                + m_Key.Substring(12, 4);
                        } else {
                            m_Key = m_Key.Substring(0, 6) + "-"
                                + m_Key.Substring(6, 4) + "-"
                                + m_Key.Substring(10, 6) + "-"
                                + m_Key.Substring(16, 4) + "-"
                                + m_Key.Substring(20, 6);
                        }
                        break;

                    case 4: //w2
                        m_Key = txtKey.Text.Replace("-", "").Trim();
                        if (m_Key.Length != 16) {
                            if (MessageBox.Show("This WarCraft II key is not the correct length." +
                                            "Continue?",
                                            "CD-Key Editor",
                                            MessageBoxButtons.YesNo,
                                            MessageBoxIcon.Exclamation,
                                            MessageBoxDefaultButton.Button2)
                                    == DialogResult.No) {
                                return;
                            }
                        }
                        foreach (char c in m_Key) {
                            if (!char.IsLetterOrDigit(c)) {
                                if (MessageBox.Show("This WarCraft II key is not valid." +
                                                "Continue?",
                                                "CD-Key Editor",
                                                MessageBoxButtons.YesNo,
                                                MessageBoxIcon.Exclamation,
                                                MessageBoxDefaultButton.Button2)
                                        == DialogResult.Yes) {
                                    break;
                                } else {
                                    return;
                                }
                            }
                        }
                        m_Key = m_Key.Substring(0, 4) + "-"
                            + m_Key.Substring(4, 4) + "-"
                            + m_Key.Substring(8, 4) + "-"
                            + m_Key.Substring(12, 4);
                        break;

                    case 5: //w3
                    case 6: //w3x
                        m_Key = txtKey.Text.Replace("-", "").Trim();
                        if (m_Key.Length != 26) {
                            if (MessageBox.Show("This WarCraft III key is not the correct length." +
                                            "Continue?",
                                            "CD-Key Editor",
                                            MessageBoxButtons.YesNo,
                                            MessageBoxIcon.Exclamation,
                                            MessageBoxDefaultButton.Button2)
                                    == DialogResult.No) {
                                return;
                            }
                        }
                        foreach (char c in m_Key) {
                            if (!char.IsLetterOrDigit(c)) {
                                if (MessageBox.Show("This WarCraft III key is not valid." +
                                                "Continue?",
                                                "CD-Key Editor",
                                                MessageBoxButtons.YesNo,
                                                MessageBoxIcon.Exclamation,
                                                MessageBoxDefaultButton.Button2)
                                        == DialogResult.Yes) {
                                    break;
                                } else {
                                    return;
                                }
                            }
                        }
                        m_Key = m_Key.Substring(0, 6) + "-"
                            + m_Key.Substring(6, 4) + "-"
                            + m_Key.Substring(10, 6) + "-"
                            + m_Key.Substring(16, 4) + "-"
                            + m_Key.Substring(20, 6);
                        break;

                }
                this.DialogResult = btnOK.DialogResult;
                this.Close();
            }
        }
    }
}
